package com.bangdream.michelia.view.activity.base;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bangdream.michelia.view.activity.currency.MainActivity;
import com.jaeger.library.StatusBarUtil;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.MainApplication;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.tool.StatusBarTool;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.utils.NetworkUtil;
import com.bangdream.michelia.utils.PublicUtil;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Mr.Wang on 2018/3/19.
 * 909732184@qq.com
 */

public abstract class BaseActivity<V,P extends BasePresenter<V>>
        extends AppCompatActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks{
    //网络请求的抽象
    public ProgressDialog pd;
    //Function是对Observable的一些基础设置
    public ObservableTransformer<Observable, ObservableSource> composeFunction;
    //重试的次数
    private final long RETRY_TIMES = 1;
    private boolean showLoading = true;
    public TextView tv_left, tv_title, tv_right;
    private LinearLayout title_bar;
    private View statusBarHeight;
    public ProgressBar pb;
    //是否需要点击空白处自动隐藏软键盘
    protected boolean isHideInput = true;
    public final String[] PicturePerms = {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};  //相机权限 扫描二维码
    private static  final int RC_CAMERA_PERM = 0x5545;           //权限申请成功失败回调码
    //需要申请的权限
    private String[] perms;
    //申请权限的提示
    private String stPermsText;
    //判断页面关闭时是否需要刷新
    public boolean isRefresh = false;
    //权限申请的回调
    private OnPermissionListener onPermissionListener;
    protected P mPresenter;
    public boolean isHideInput() {
        return isHideInput;
    }

    public void setHideInput(boolean hideInput) {
        isHideInput = hideInput;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        setContentView(getLayout());
        findId();
        logic();
        setListener();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        init();
        setContentView(getLayout());
        findId();
        logic();
        setListener();
    }
    public abstract int getLayout();
    public abstract void findId();
    public abstract void setListener();
    public abstract void logic();
    public abstract P createPresenter();
    private void init() {
        MainApplication.addActivity(this);
        StatusBarUtil.setColorNoTranslucent(this, ContextCompat.getColor(this, R.color.text_on));
        pd = new ProgressDialog(this);
        //点击空白处不消失
        pd.setCanceledOnTouchOutside(false);
        composeFunction = new ObservableTransformer<Observable, ObservableSource>() {
            @Override
            public ObservableSource apply(Observable observable) {
                //retry方法是设置重试次数 不指定默认为0
                return observable.retry(RETRY_TIMES)
                        //将被观察者放在子线程，将观察者放在主线程
                        .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                        //doOnSubscribe是在事件发送前进行的操作，所以我们可以做一些初始化的工作
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (NetworkUtil.isNetworkAvailable(BaseActivity.this)) {
                                    if (showLoading) {
                                        if(pd != null && !pd.isShowing()){
                                            pd.show();
                                        }
                                    }
                                } else {
                                    Toast.makeText(MainApplication.getContext(), "网络连接异常，请检查网络", Toast.LENGTH_LONG).show();
                                }
                            }
                        });
            }
        };
        if(mPresenter==null) {
            mPresenter = createPresenter();
        }
        if(mPresenter!=null) {
            mPresenter.attach((V) this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mPresenter!=null)
        mPresenter.detach();
    }

    /**
     * 初始化titlebar，该方法只有在标题栏布局符合此规则时才能调用
     * @param left titlebar左按钮
     * @param title titlebar标题
     * @param right titlebar 右按钮
     * @param onClickListener 左右按钮点击事件
     */
    public void initTitleBar(String left,String title,String right,View.OnClickListener onClickListener){
        tv_left = findViewById(R.id.tv_left);//返回按钮
        tv_title = findViewById(R.id.tv_title);//标题
        tv_right = findViewById(R.id.tv_right);//更多(右侧)按钮
        pb = findViewById(R.id.pb);// 标题栏数据加载ProgressBar

        if(!TextUtils.isEmpty(left)){
            tv_left.setText(left);
            tv_left.setVisibility(View.VISIBLE);
            tv_left.setOnClickListener(onClickListener);
        }

        if(!TextUtils.isEmpty(title)){
            tv_title.setText(title);
        }

        if(!TextUtils.isEmpty(right)){
            tv_right.setText(right);
            tv_right.setVisibility(View.VISIBLE);
            tv_right.setOnClickListener(onClickListener);
        }
    }
    //透明状态栏的头部布局
    public void initTitleBar(String left, String title, String right, View.OnClickListener onClickListener, boolean isNoStatelessBar){
        if(isNoStatelessBar){
            title_bar = findViewById(R.id.title_bar);
            statusBarHeight = findViewById(R.id.statusBarHeight);
            ViewGroup.LayoutParams titleBarLayoutParams = title_bar.getLayoutParams();
            titleBarLayoutParams.height = PublicUtil.dip2px(this,50)+ StatusBarTool.getStatusHeight(this);
            statusBarHeight.getLayoutParams().height = StatusBarTool.getStatusHeight(this);
        }
        initTitleBar(left,title,right,onClickListener);
    }
    /**
     * 如果子类支持点击左上角返回按钮返回，则在子类的onClick方法中需添加super.onClick(View view);
     */
    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.tv_left:
                finish();
                break;
        }
    }

    /**
     * 点击空白处隐藏软键盘
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        //防止连续点击
       if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//            if (ClickUtils.isFastDoubleClick()) {
//                //如果1秒内被连续点击则消费掉事件 不下发
//                return true;
//            }
            if (isHideInput) {
                View view = getCurrentFocus();
                if (isHideInput(view, ev)) {
                    HideSoftInput(view.getWindowToken());
                }
            }
        }

        return super.dispatchTouchEvent(ev);
    }
    // 判定是否需要隐藏
    public boolean isHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = { 0, 0 };
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top
                    && ev.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
    // 隐藏软键盘
    public void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    public void setLoadingFlag(boolean show) {
        showLoading = show;
    }


    /**
     * @param perms 需要申请的权限
     * @param stPermsText 提示文本
     * @param onPermissionListener 回调
     */
    public void PermissionApplication(String[] perms, String stPermsText, OnPermissionListener onPermissionListener)
    {
        this.perms = perms;
        this.stPermsText = stPermsText+"";
        this.onPermissionListener = onPermissionListener;
        if (perms!=null&& EasyPermissions.hasPermissions(this, perms)) {
            //已经有访问文件的权限了，可以使用该权限完成app的相应的操作了
            if(onPermissionListener!=null)
            {
                onPermissionListener.onSuccess();
            }
        }
        else {
            // app还没有使用摄像头的权限，调用该方法进行申请，同时给出了相应的说明文案，提高用户同意的可能性
            if(perms!=null){
                EasyPermissions.requestPermissions(BaseActivity.this, stPermsText,
                        RC_CAMERA_PERM, perms);
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发给EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        // 权限被授予
        // ...
        PermissionApplication(this.perms,stPermsText,onPermissionListener);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        // 权限被拒绝
        // ...
//        EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
//                "为了您的正常使用，美脚玉足吧需要获得文件访问权限，请您进去设置->应用->权限进行设置",
//                R.string.setting, R.string.cancel, perms);
        if(onPermissionListener!=null) {
            onPermissionListener.onFail();
        }
        if(stPermsText!=null) {
            showText(stPermsText);
        }
        //以下代码可以跳转到应用详情，可以通过应用详情跳转到权限界面(6.0系统测试可用)
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", this.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", this.getPackageName());
        }
        startActivity(localIntent);
    }


    @Override
    protected void onStop() {
        super.onStop();
        // 在 onStop 时释放掉播放器
        //NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
    }
    @Override
    public void finish() {
        if(isRefresh){
            setResult(Activity.RESULT_OK);
        }
        super.finish();
    }
    protected void showText(String text){
        //一段时间内只显示一条提示 不形成队列
        ToastUtil.showShortToast(this,text);
        //Toast.makeText(this,text,Toast.LENGTH_LONG).show();
    }

    //https://blog.csdn.net/yp0403110221/article/details/49851785
    protected final  <T> T $(int id){
        return (T)findViewById(id);
    }


    @Override
    public void onBackPressed() {
        // 在全屏或者小窗口时按返回键要先退出全屏或小窗口，
        // 所以在 Activity 中 onBackPress 要交给 NiceVideoPlayer 先处理。
        //if (NiceVideoPlayerManager.instance().onBackPressd()) return;
        super.onBackPressed();
    }

    //检查是否为空 为空则输出描述返回true
    protected boolean checkStrEmpty(String str, String display) {
        if (TextUtils.isEmpty(str)) {
            showText(display);
            return true;
        }
        return false;
    }
}
